<template>
  <div class="box">
    <div id="container"></div>
    <div class="tabs">
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="风景" name="first" class="scene">
          <ol class="scene-name">
            <li
              class="tabCentent"
              v-for="(item,index) in sceneryList"
              :key="index"
              @mouseover="mouseoverTabCentent($event,index)"
              @mouseout="mouseoutTabCentent"
              ref="sceneNameLi"
            >
              <span>{{item.name}}</span>
            </li>
          </ol>
          <ol ref="sceneDis">
            <li ref="sceneDisLi" v-for="(item,index) of getSecDistance" :key="index">{{item}}</li>
          </ol>
        </el-tab-pane>
        <el-tab-pane label="交通" name="second">
          <ol class="traffic-name" ref="trafficName">
            <li
              ref="trafficNameLi"
              class="tabCentent"
              v-for="(item,index) in trafficList"
              :key="index"
              @mouseover="mouseoverTabCentent($event,index)"
              @mouseout="mouseoutTabCentent"
            >
              <span>{{item.name}}</span>
            </li>
          </ol>
          <ol ref="trafficDis">
            <li ref="trafficDisLi" v-for="(item,index) of getTraDistance" :key="index">{{item}}</li>
          </ol>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //当前城市
      cityName: "",
      activeName: "first",
      //风景列表
      sceneryList: [],
      //风景距离列表
      sceneDisList: [],
      //交通列表
      trafficList: [],
      //交通距离列表
      distanceList: [],
      renderSecList: [],
      jingdu: "",
      weidu: "",
      flag: true,
      flag2: true,
      markList1: [],
      markList2: [],
    };
  },
  computed: {
    getTraDistance() {
      let arr = this.distanceList.map((spot) => {
        // //(spot);
        let p1 = [spot.location.R, spot.location.Q];
        let p2 = [this.jingdu, this.weidu];
        var dis = AMap.GeometryUtil.distance(p1, p2);
        dis = (dis / 1000).toFixed(2);
        return dis + "公里";
      });
      return arr;
      // 返回 p1 到 p2 间的地面距离，单位：米
    },
    getSecDistance() {
      let arr = this.sceneDisList.map((spot) => {
        // //(spot);
        let p1 = [spot.location.R, spot.location.Q];
        let p2 = [this.jingdu, this.weidu];
        var dis = AMap.GeometryUtil.distance(p1, p2);
        dis = (dis / 1000).toFixed(2);
        return dis + "公里";
      });
      return arr;
    },
  },
  updated() {
    // console.log("---------------updated----------------");
    // //(this.$refs);
    // //("this.domObject = this.$refs;");

    if (this.$refs.trafficDisLi && this.flag) {
      // //("循环遍历----------------------改变DOM");
      for (var i = 0; i < this.$refs.trafficDisLi.length; i++) {
        // //(this.$refs.trafficDisLi[i]);
        let span = document.createElement("span");
        let text = this.$refs.trafficDisLi[i].innerText;
        span.innerText = text;

        this.$refs.trafficNameLi[i].appendChild(span);
        // //(this.$refs.trafficNameLi[i]);
      }
      this.$refs.trafficDis.innerHTML = "";
      this.flag = false;
    }

    if (this.$refs.sceneDisLi && this.flag2) {
      // //("循环遍历----------------------改变DOM");
      for (var i = 0; i < this.$refs.sceneDisLi.length; i++) {
        let span = document.createElement("span");
        let text = this.$refs.sceneDisLi[i].innerText;
        span.innerText = text;
        span.className = "scene-kilo";
        // console.log(span);
        this.$refs.sceneNameLi[i].appendChild(span);
        // // //(this.$refs.trafficNameLi[i]);
      }
      this.$refs.sceneDis.innerHTML = "";
      this.flag2 = false;
    }
  },
  mounted() {
    if (!window.AMap) {
      // 第一次加载
      window.onLoad = () => {
        //箭头函数保留外部的this;
        this.init();
      };

      var url =
        "https://webapi.amap.com/maps?v=1.4.15&key=696fc5bf54b56dbefae3f32bec092a6c&plugin=AMap.PlaceSearch&callback=onLoad";
      var jsapi = document.createElement("script");
      jsapi.charset = "utf-8";
      jsapi.src = url;
      document.head.appendChild(jsapi);
    } else {
      this.init();
    }
  },
  methods: {
    async init() {
      //从路由获取酒店的id
      let hotelId = this.$route.query.id;
      //获取酒店位置
      const backData = (
        await this.$store.dispatch("hotel/asyncGetCurrentHotelMsg", hotelId)
      ).data.data;
      //渲染风景
      console.log("---------酒店数据------");
      console.log(backData);
      //获取城市名
      let cityName = backData[0].city.name;
      this.cityName = cityName;

      let jingdu = backData[0].location.longitude.toFixed(3);
      let weidu = backData[0].location.latitude.toFixed(3);

      this.jingdu = jingdu;
      this.weidu = weidu;
      let map = new AMap.Map("container");
      this.map = map;
      // console.log(this.map);

      var content =
        '<div class=" hotel-marker"><i class="iconfont icon-zhongdian hotel-position"></i></div>';
      let marker1 = new AMap.Marker({
        position: new AMap.LngLat(jingdu, weidu), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        title: backData[0].name,
        content: content,
        // center: [116.397428, 39.90923], //地图中心点
        zoom: 10, //地图显示的缩放级别
        autoFitView: true,
      });

      // 将创建的点标记添加到已有的地图实例：
      map.add(marker1);
      //进来加载风景地图标点；
      this.renderScenery();
      // this.renderStations();
    },
    //渲染风景的方法
    renderScenery() {
      AMap.service(["AMap.PlaceSearch"], () => {
        //构造地点查询类
        var placeSearch = new AMap.PlaceSearch({
          type: "风景", // 兴趣点类别
          pageSize: 5, // 单页显示结果条数
          pageIndex: 1, // 页码
          city: this.cityName, // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          map: this.map, // 展现结果的地图实例
          //panel: "panel", // 结果列表将在此容器中进行展示。
          autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });

        //构建一个自定义信息窗体；
        var infoWindow = new AMap.InfoWindow({
          offset: new AMap.Pixel(0, -30),
        });

        var cpoint = [this.jingdu, this.weidu]; //中心点坐标
        placeSearch.searchNearBy("", cpoint, 2000, (status, result) => {
          if (status === "complete" && result.info === "OK") {
            //保存渲染风景的数据；

            this.sceneryList = result.poiList.pois;

            var stationArr = result.poiList.pois;
            var searchNum = stationArr.length;

            //保存距离数据
            this.sceneDisList = result.poiList.pois;
            this.renderSecList = this.getSecDistance;

            console.log(stationArr);
            /*AMap中保存着多个静态方法都可以绑定地图实例，若是构造函数中绑定了多个地图实例对象，后创建的会覆盖先创建的，
            这里若是需要自定义信息窗体，在每个marker上绑定infoWindow的方法即可*/
            if (searchNum > 0) {
              //("查询结果：共" + searchNum + "个相关站点");
              for (var i = 0; i < stationArr.length; i++) {
                let content = `<i class="station-marker iconfont icon-ditudingweidian-weixuanzhong"><span>${
                  i + 1
                }</span></i>`;
                var marker = new AMap.Marker({
                  cursor: "move",
                  // content: content,
                  // center: [116.397428, 39.90923], //地图中心点
                  // zoom: 14, //地图显示的缩放级别
                  // offset: new AMap.Pixel(-16, -32),
                  position: stationArr[i].location,

                  title: stationArr[i].name,
                  autoFitView: true,
                });

                marker.on("mousemove", (backData) => {
                  infoWindow.setContent(backData[0]);
                  infoWindow.open(this.map, marker.getPosition());
                });
                marker.emit("mousemove", { target: marker });

                this.marker = marker;

                //将marker加入marklist以便于后面鼠标移入事件获取；
                this.markList1.push(marker);

                //构建信息窗体
                // var infoWindow = new AMap.InfoWindow({
                //   autoMove: true,
                //   offset: { x: 0, y: -30 },
                // });
                // infoWindow.open(this.map, this.marker.getPosition());
                // console.log("--------------信息窗体---------------");
                // console.log(infoWindow);

                // infoWindow.setContent((backData) => {
                //   var s = [];
                //   s.push("<b>名称：" + backData[0].name + "</b>");
                //   s.push("地址：" + backData[0].address);
                //   s.push("商业区：" + backData[0].business_area);
                //   s.push("详情：" + backData[0].creation_time);
                //   return s.join("<br>");
                // });

                // marker.info = new AMap.InfoWindow({
                //   content: stationArr[i].address,
                //   offset: new AMap.Pixel(0, -30),
                // });

                let stationLocal = stationArr[i].location;
                this.positionMove(stationLocal);
              }
            }
          } else {
            //("此站点没有数据");
          }
        });
      });

      // console.log("执行setFitView");
      // console.log(this.map);
      this.map.setFitView();
    },
    //渲染交通站点的方法
    renderStations() {
      AMap.service(["AMap.PlaceSearch"], () => {
        //构造地点查询类
        var placeSearch = new AMap.PlaceSearch({
          type: "交通", // 兴趣点类别
          pageSize: 5, // 单页显示结果条数
          pageIndex: 1, // 页码
          city: this.cityName, // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          // map: this.map, // 展现结果的地图实例
          //panel: "panel", // 结果列表将在此容器中进行展示。
          autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });

        var cpoint = [this.jingdu, this.weidu]; //中心点坐标
        placeSearch.searchNearBy("", cpoint, 2000, (status, result) => {
          // console.log(status);
          // console.log(result);
          if (status === "complete" && result.info === "OK") {
            //渲染交通的数据；
            this.trafficList = result.poiList.pois;
            //保存距离数据
            this.distanceList = result.poiList.pois;

            var stationArr = result.poiList.pois;
            var searchNum = stationArr.length;

            if (searchNum > 0) {
              //("查询结果：共" + searchNum + "个相关站点");
              for (var i = 0; i < stationArr.length; i++) {
                let content = `<i class="station-marker iconfont icon-ditudingweidian-weixuanzhong"><span>${
                  i + 1
                }</span></i>`;
                var marker = new AMap.Marker({
                  cursor: "move",
                  content: content,
                  // center: [116.397428, 39.90923], //地图中心点
                  // zoom: 14, //地图显示的缩放级别
                  // offset: new AMap.Pixel(-16, -32),
                  position: stationArr[i].location,
                  map: this.map,
                  title: stationArr[i].name,
                  autoFitView: true,
                });
                this.marker = marker;
                this.markList2.push(marker);
                // console.log("这里是marker数据");
                // console.log(this.marker);

                marker.info = new AMap.InfoWindow({
                  content: stationArr[i].address,
                  offset: new AMap.Pixel(0, -30),
                });
                // console.log("-------------打印marker.info----------");
                // console.log(marker.info);
                // marker.on("mouseover", function (e) {
                //   e.target.info.open(this.map, e.target.getPosition());
                // });

                // 设置点标记的动画效果，此处为弹跳效果
                // marker.setAnimation("AMAP_ANIMATION_BOUNCE");

                let stationLocal = stationArr[i].location;
                this.positionMove(stationLocal);
              }
            }
          } else {
            //("此站点没有数据");
          }
        });
      });

      // console.log("执行setFitView");
      // console.log(this.map);
      this.map.setFitView();
    },
    //自定义信息窗体的方法
    markerClick(map) {},

    positionMove(stationLocal) {
      // console.log("-----------------交通站点渲染-----------------");
      // console.log(stationLocal);
      // console.log(AMap);
      // console.log(this.marker);
      AMap.event.addListener(this.marker, "mouseover", () => {
        //("执行鼠标移入");
        //(stationLocal);
        // var zoom = Math.floor(Math.random() * 7) + 11;
        var lng = stationLocal.lng;
        var lat = stationLocal.lat;
        this.map.setZoomAndCenter(16, [lng, lat]); //同时设置地图层级与中心点
        // //(
        //   `当前层级已设为${zoom}级，中心点已设为 ${lng.toFixed(
        //     6
        //   )},${lat.toFixed(6)}`
        // );
      });
      this.AMap = AMap;
      // console.log("获取AMap");
      // console.log(AMap);
    },

    handleTabClick(e) {
      // console.log(e.name);
      // console.log(this.map);
      // 清除地图上所有添加的覆盖物;
      if (e.name == "second") {
        this.map.clearMap();
        this.renderStations();
      } else {
        this.map.clearMap();
        this.renderScenery();
      }
    },
    mouseoverTabCentent(e, index) {
      // console.log("触发mouseoverTabCentent事件");

      if (e.target.parentNode.className == "scene-name" && this.markList1) {
        this.AMap.event.trigger(this.markList1[index], "mouseover");
      } else if (
        e.target.parentNode.className == "traffic-name" &&
        this.markList2
      ) {
        this.AMap.event.trigger(this.markList2[index], "mouseover");
      }

      e.target.style.background = "rgba(0, 0, 0, 0.1)";
    },
    mouseoutTabCentent(e) {
      e.target.style.background = "#fff";
    },
  },
};
</script>

<style lang="less" scoped>
.box {
  display: flex;
  justify-content: space-between;

  #container {
    width: 650px;
    height: 360px;
  }
  .tabs {
    .el-tabs {
      width: 333px;
      margin: 0 0;

      ol {
        width: 100%;
        height: 310px;
        overflow-y: auto;
        .tabCentent {
          display: flex;
          justify-content: space-between;
          padding-bottom: 15px;
          padding-top: 10px;
          color: #666666;
          font-size: 14px;
          padding-right: 15px;
          cursor: pointer;

          span {
            background: none !important;
            margin: 0 15px;
          }
        }
      }
    }
  }
}
.scene-kilo {
  background: none !important;
}
/deep/ .hotel-position {
  font-size: 34px !important;
}
/deep/ .hotel-marker {
  color: red;
  font-size: 40px !important;
}
/deep/ .station-marker {
  position: relative;
  font-size: 40px;
  color: #4297fc;
  span {
    position: absolute;
    color: #fff;
    font-weight: 600;
    left: 17px;
    top: 5px;
    font-size: 12px;
  }
}
/deep/ .el-tabs {
  height: 360px;
}
</style>